package net.hn.hnms.biz.dust.service;

import lombok.RequiredArgsConstructor;
import net.hn.hnms.biz.api.feign.model.DataStateVo;
import net.hn.hnms.biz.api.mine.RemoteMineInfoService;
import net.hn.hnms.biz.api.mine.model.DustIndicatorVo;
import net.hn.hnms.biz.common.jpa.utils.ResponsePage;
import net.hn.hnms.biz.dust.domain.DwdCoalSeamInfoEntity;
import net.hn.hnms.biz.dust.repository.CoalSeamInfoRepository;
import net.hn.hnms.biz.dust.vo.ChartVo;
import net.hn.hnms.biz.dust.vo.FcfzData;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 智呈物联 pan'sx
 * 2022/10/20 9:44
 * 1.0 version
 */
@Service
@RequiredArgsConstructor
public class FcfzService {
    private final JdbcTemplate jdbcTemplate;
    private final RemoteMineInfoService remoteMineInfoService;
    private final CoalSeamInfoRepository coalSeamInfoRepository;


    public ChartVo alarmTrend(String type, String mineCode) {
        Calendar calendar = Calendar.getInstance();
        Date endTime = calendar.getTime();
        if ("月".equals(type)) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
        }
        List<String> xDate = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        while (calendar.getTime().getTime() <= endTime.getTime()) {
            xDate.add(sdf.format(calendar.getTime()));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        }
        if (StringUtils.isNotBlank(mineCode)) {
            mineCode = " and mine_code='" + mineCode + "'";
        } else {
            mineCode = "";
        }
        String sql = "SELECT to_char(data_time,'yyyy-mm-dd') as day,count(1) as count FROM \"dwd_fcfz_his_sensormonitor\" " +
                "where data_time>'%s' and point_name like '%%粉尘' and point_value >40000 %s " +
                "GROUP BY day";
        String[] values = new String[xDate.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = "0";
        }
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(String.format(sql, xDate.get(0), mineCode));
        for (Map<String, Object> map : maps) {
            values[xDate.indexOf(map.get("day"))] = map.get("count") + "";
        }
        ChartVo alarmTrendVo = new ChartVo();
        alarmTrendVo.setXData(xDate);
        alarmTrendVo.setValeus(Arrays.asList(values));
        return alarmTrendVo;

    }

    public ChartVo sprayAlarmTrend(String type, String mineCode) {
        Calendar calendar = Calendar.getInstance();
        Date endTime = calendar.getTime();
        if ("月".equals(type)) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
        }
        List<String> xDate = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        while (calendar.getTime().getTime() <= endTime.getTime()) {
            xDate.add(sdf.format(calendar.getTime()));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        }
        if (StringUtils.isNotBlank(mineCode)) {
            mineCode = " and mine_code='" + mineCode + "'";
        } else {
            mineCode = "";
        }
        String sql = "SELECT to_char(data_time,'yyyy-mm-dd') as day,count(1) as count FROM dwd_fcfz_his_sensormonitor " +
                "where data_time>'%s' and point_name like '%%喷淋' and point_status_code !='0' %s " +
                "GROUP BY day";
        String[] values = new String[xDate.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = "0";
        }
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(String.format(sql, xDate.get(0), mineCode));
        for (Map<String, Object> map : maps) {
            values[xDate.indexOf(map.get("day"))] = map.get("count") + "";
        }
        ChartVo alarmTrendVo = new ChartVo();
        alarmTrendVo.setXData(xDate);
        alarmTrendVo.setValeus(Arrays.asList(values));
        return alarmTrendVo;
    }

    public ChartVo monitorTrend(String type, String pointCode, String mineCode) {
        Calendar calendar = Calendar.getInstance();
        Date endTime = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> xDate = new ArrayList<>();
        if ("月".equals(type)) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        } else {
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) - 7);
        }
        while (calendar.getTime().getTime() <= endTime.getTime()) {
            xDate.add(sdf.format(calendar.getTime()));
            calendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH) + 1);
        }
        if (StringUtils.isNotBlank(mineCode)) {
            mineCode = " and mine_code='" + mineCode + "'";
        } else {
            mineCode = "";
        }
        String sql = "SELECT to_char(data_time,'yyyy-mm-dd') as sj,max(point_value) valuess FROM " +
                "\"dwd_fcfz_his_sensormonitor\" where data_time>'%s'  " +
                "and point_code ='%s' %s  GROUP BY sj";

        List<Map<String, Object>> maps = jdbcTemplate.queryForList(String.format(sql, xDate.get(0), pointCode, mineCode));
        String[] values = new String[xDate.size()];
        for (Map<String, Object> map : maps) {
            values[xDate.indexOf(map.get("sj"))] = map.get("valuess") + "";
        }
        ChartVo alarmTrendVo = new ChartVo();
        alarmTrendVo.setXData(xDate);
        alarmTrendVo.setValeus(Arrays.asList(values));
        return alarmTrendVo;
    }

    public ResponsePage<FcfzData> pageList(int pageNum, int pageSize,
                                           String beginTime, String endTime, String pointCode, String mineCode) {
        String sql = "SELECT %s FROM \"dwd_fcfz_his_sensormonitor\" " +
                "t1 join dwd_fcfz_base_sensorinfo t2 on (t2.mine_code=t1.mine_code and t2.point_code=t1.point_code) where 1=1 %s ";

        String column = " t1.mine_code as mineCode,t1.point_name as pointName,t2.point_type_name as pointTypeName,t2.point_monitor_location as " +
                "pointMonitorLocation,t1.value_unit unit ,t1.point_value as pointValue,t1.point_status_name as pointStatusName, t1.data_time as dataTime ";
        StringBuilder sb = new StringBuilder(sql);
        if (StringUtils.isNotBlank(beginTime)) {
            sb.append(" and t1.data_time >= '").append(beginTime).append("' ");
        }
        if (StringUtils.isNotBlank(endTime)) {
            sb.append(" and t1.data_time < '").append(endTime).append("' ");
        }
        if (StringUtils.isNotBlank(pointCode)) {
            sb.append(" and t1.point_code = '").append(pointCode).append("' ");
        }
        if (StringUtils.isNotBlank(mineCode)) {
            mineCode = " and t1.mine_code='" + mineCode + "' and t2.mine_code='" + mineCode + "' ";
        } else {
            mineCode = "";
        }
        Integer count = jdbcTemplate.queryForObject(String.format(sb.toString(), "count(1)", mineCode), Integer.class);
        ResponsePage<FcfzData> responsePage;
        if (count > 0) {

            sb.append(" order by data_time desc  limit ").append(pageSize).append(" offset ").append(pageNum * pageSize);
            List<FcfzData> query = jdbcTemplate.query(String.format(sb.toString(), column, mineCode), new BeanPropertyRowMapper<>(FcfzData.class));
            query.forEach(s -> {
                if ("状态".equals(s.getPointName())) {
                    s.setValue(s.getPointValue().doubleValue() > 0 ? "开" : "关");
                } else if ("洒水阀门".equals(s.getPointName())) {
                    s.setValue(s.getPointValue().doubleValue() > 0 ? "开" : "关");
                } else {
                    s.setValue(s.getPointValue() + "");
                }
            });
            responsePage = new ResponsePage<FcfzData>(query, count);
        } else {
            responsePage = new ResponsePage<FcfzData>(new ArrayList(), 0);
        }
        return responsePage;

    }

    public List<DustIndicatorVo> score(String[] containOrgs) {
        List<DustIndicatorVo> list = new ArrayList<>();
        for (String org : containOrgs) {
            R<DustIndicatorVo> indicator = remoteMineInfoService.dustIndicator(org);
            if (indicator.getCode() == Constants.SUCCESS) {
                DustIndicatorVo data = indicator.getData();
                list.add(data);
            }
        }
        return list;
    }

    public List<DataStateVo> getMaxTime(String mineCode, String companyCode) {
        String sql = "SELECT mine_code as mineCode,max(create_time) as maxTime  FROM dwd_fcfz_now_sensormonitor where 1=1 %s %s group by mine_code";
        if (StringUtils.isNotBlank(mineCode)) {
            mineCode = "and mine_code='" + mineCode + "' ";
        } else {
            mineCode = "";
        }
        if (StringUtils.isNotBlank(companyCode) && StringUtils.isBlank(mineCode)) {
            companyCode = "and company_code='" + companyCode + "' ";
        } else {
            companyCode = "";
        }
        List<DataStateVo> query = jdbcTemplate.query(String.format(sql, mineCode, companyCode), new BeanPropertyRowMapper<>(DataStateVo.class));
        return query;
    }

    public DwdCoalSeamInfoEntity coalSeamInfo(String mineCode) {
        return coalSeamInfoRepository.findFirstByDelFlagAndMineCode("0", mineCode);
    }

}
